import axios from 'axios'
import config from './config.js'
import qs from 'qs'
import { Toast } from 'vant';

export default function $axios(options) {
    return new Promise((resolve, reject) => {
        const instance = axios.create({//创建一个请求
            baseURL: config.baseUrl,
            headers: {}
        })

        //请求拦截
        instance.interceptors.request.use(
            conf => {
                //带上token给后端秘钥、令牌
                if (config.method.toLocaleLowerCase === 'post' || config.method.toLocaleLowerCase === 'put' || config.method.toLocaleLowerCase === 'delete') {
                    conf.data = qs.stringify(conf.data)
                }
                return conf
            },
            error => {
                console.log(error,'请求拦截');
            }
        )

        //响应拦截,后端返回的响应
        instance.interceptors.response.use(
            response => {
                let data = response.data

                switch (data.code) {//业务逻辑错误
                    case 0:
                        const message = data.msg || 'Error'
                        Toast.fail({
                            message,
                            duration: 1000
                        })
                        return Promise.reject(message)
                    default:

                }
                return data
            },
            error => {//后端响应错误、服务端错误
                if (error && error.response) {
                    switch (error.response.status) {//http
                        case 400:
                            error.message = '请求错误'
                            break

                        case 401://未有权限
                            error.message = '未授权请登录'
                            break

                        case 404://未有权限
                            error.message = '请求地址出错'
                            break
                        default:
                    }
                }
                return Promise.reject(error)
            }
        )
        //发请求
        instance(options)
            .then(res => {
                resolve(res)
            })
            .catch(error=> {
                reject(error)
            }) 
    })

}
